package com.app.shiro;

import com.sys.menu.service.SysMenuService;
import com.sys.user.entity.SysUser;
import com.sys.user.service.SysUserService;
import com.sys.userrole.service.SysUserRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * shiro Realm
 *
 * @author
 */
public class MyRealm extends AuthorizingRealm {

    /**
     * 用户服务
     */
    @Autowired
    SysUserService userService;
    /**
     * 用户角色服务
     */
    @Autowired
    SysUserRoleService sysUserRoleService;
    /**
     * 角色菜单服务
     */
    @Autowired
    SysMenuService sysMenuService;

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken user = (UsernamePasswordToken) token;
        Map map = new HashMap(10);
        map.put("user_name", user.getUsername());
        List<SysUser> list = (List)userService.selectByMap(map);
        if (list == null || list.isEmpty()) {
            throw new UnknownAccountException();
        }
        SysUser sysUser = list.get(0);
        if (!sysUser.getUserState().equals("1")) {
            throw new LockedAccountException();
        }
        //用户名，数据库中的密码,reaml名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), getName());
        return info;
    }


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = sysUserRoleService.findRolesByUserId(sysUser.getId());
        Set<String> permissions = sysMenuService.findMenusByUserId(sysUser.getId());
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }


}
